package com.blast.manager.presenter

import android.content.Context
import android.text.TextUtils
import com.blast.manager.blast.BlastActivity
import com.blast.manager.blast.presenter.BlastSerialPresenter
import com.blast.manager.net.presenter.NetCheckChargePresenter
import com.wxl.common.AppContext
import com.wxl.common.life.ViewModelQuick
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.entity.UnApplyBlastEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.ObservableUtil
import com.wxl.common.viewmodel.AbsPresenter
import com.wxl.common.wiget.ProgressUpdatePop
import io.reactivex.ObservableOnSubscribe

class CheckLeiGuanAuthPresenter : AbsPresenter() {

    companion object {
        interface OnCheckResultCallback {
            fun onCheckResult(
                data: List<LeiGuanEntity>,
                noAuthData: List<LeiGuanEntity>,
                mTermNum: Int
            )
        }
    }

    lateinit var context: Context
    lateinit var mOnCheckResultCallback: OnCheckResultCallback
    val data: ArrayList<LeiGuanEntity> = arrayListOf()

    private var isDelayPlan = false
    private var isBlast = false

    override fun onCreated(vararg args: Any) {
        context = args[0] as Context
        mOnCheckResultCallback = args[1] as OnCheckResultCallback
        isBlast = args[2] as Boolean
        isDelayPlan = args[3] as Boolean

        data.clear()

        ProgressUpdatePop.updateProgress(0, "正在进行授权检查...", "授权检查", 100)
        DBHelper.queryLeiGuanEntity(object :
            ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                if (t.isNotEmpty()) {
                    data.addAll(t)
                    if(isBlast&&isDelayPlan){
                        (context as BlastActivity).addLog("充电起爆",0,"正在进行授权验证")
                        ViewModelQuick.get((context as BlastActivity),BlastSerialPresenter::class.java)
                            .sendAuthProve(object : BlastSerialPresenter.OnAuthDelayCallback{

                                override fun onAuthDelayResult() {
                                    ProgressUpdatePop.updateProgress(100, "授权验证成功...", "授权验证", 101)
                                    (context as BlastActivity).dismissClearAllPop()
                                    (context as BlastActivity).showChargeReadyLayout()
                                }

                                override fun onChargeProgress(p: Int, sub: String, max: Int) {
                                    ProgressUpdatePop.updateProgress(p, sub, "授权检查", max+1)
                                }

                                override fun onVoltageElectricChanged(
                                    mVoltage: Int,
                                    mElectric: Int
                                ) {
                                    ViewModelQuick.get((context as BlastActivity),
                                        NetCheckChargePresenter::class.java).onChargeElectricChanged(mVoltage,mElectric)
                                }

                                override fun onChargeProgressError(sub: String) {
                                    ProgressUpdatePop.updateProgress(-1, sub, "授权检查", 100)
                                    delayEnd(arrayListOf(),-1)
                                }
                            })
                    } else {
                        startAuthCheck()
                    }
                } else {
                    mOnCheckResultCallback.onCheckResult(data, data, 0)
                }
            }
        })
    }


    private fun startAuthCheck(){
        ObservableUtil.doNext(ObservableOnSubscribe { oe ->
            data.forEach {
                if (TextUtils.isEmpty(it.password)) {
                    oe.onNext(true)
                    return@ObservableOnSubscribe
                }
            }
            oe.onNext(false)
        }, object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                if (t) {
                    checkDbAuthFile()
                } else {
                    ProgressUpdatePop.updateProgress(100, "完成授权检查...", "授权检查", 101)
                    delayEnd(arrayListOf(),0)
                }
            }
        })

    }

    private fun delayEnd(mNoAuthorizeList:List<LeiGuanEntity>,mTermNum:Int){
        ObservableUtil.delay(2000, Runnable {
            mOnCheckResultCallback.onCheckResult(data,mNoAuthorizeList,mTermNum)
        })
    }

    /**
     * 检查本地是否有对应的授权文件
     */
    private fun checkDbAuthFile() {
        ProgressUpdatePop.updateProgress(20, "正在进行授权检查...", "授权检查", 100)
        DBHelper.queryAppledBlastData(object :
            ObservableUtil.Companion.OnNextCallback<List<UnApplyBlastEntity>>() {
            override fun onNext(t: List<UnApplyBlastEntity>) {
                if (t.isNotEmpty()) {
                    checkDbAuthFileDue(t)
                } else {
                    checkAuthCase()
                }
            }
        })
    }

    /**
     * 检查授权文件是否过期
     */
    private fun checkDbAuthFileDue(t: List<UnApplyBlastEntity>) {
        ProgressUpdatePop.updateProgress(40, "正在进行授权检查...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            val regular = arrayListOf<UnApplyBlastEntity>()
            t.forEach {
                it.takeIf {
                    it.lgs != null && it.lgs.lg != null && it.lgs.lg.isNotEmpty() && !TextUtils.isEmpty(
                        it.lgs.lg[0].yxq
                    ) && it.lgs.lg[0].yxq.toLong() > System.currentTimeMillis()
                }?.apply {
                    regular.add(this)
                }
            }
            it.onNext(regular)
        }, object : ObservableUtil.Companion.OnNextCallback<List<UnApplyBlastEntity>>() {
            override fun onNext(t: List<UnApplyBlastEntity>) {
                if (t.isNotEmpty()) {
                    auth(t)
                } else {
                    checkAuthCase()
                }
            }
        })
    }

    /**
     * 授权
     */
    private fun auth(data: List<UnApplyBlastEntity>) {
        ProgressUpdatePop.updateProgress(60, "正在进行授权...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            var update = false
            data.forEach { abe ->
               this.data.forEach {
                    if (TextUtils.equals(abe.lgs.lg[0].uid, it.UID)) {
                        it.password = abe.lgs.lg[0].gzm
                        update = true
                    }
                }
            }
            it.onNext(update)
        }, object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                if (t) {
                    AppContext.appContext.saveAuthDmInfo(data[0].licenseFileModel)
                    DBHelper.updateLeiGuan(object :
                        ObservableUtil.Companion.OnNextCallback<Boolean>() {
                        override fun onNext(t: Boolean) {
                            checkAuthCase()
                        }
                    }, *this@CheckLeiGuanAuthPresenter.data.toTypedArray())
                } else {
                    checkAuthCase()
                }
            }
        })

    }


    /**
     * 检查授权完成后的情况
     */
    private fun checkAuthCase() {
        var mTermNum = 0
        ProgressUpdatePop.updateProgress(80, "正在进行授权检查...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            val mNoAuthorizeList = arrayListOf<LeiGuanEntity>()
            this@CheckLeiGuanAuthPresenter.data.forEach {
                if (TextUtils.isEmpty(it.password)) {
                    mNoAuthorizeList.add(it)
                }
                if (it.term != 0.0) {
                    mTermNum++
                }
            }
            it.onNext(mNoAuthorizeList)
        }, object : ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                if (t.isEmpty()) {
                    ProgressUpdatePop.updateProgress(100, "已完成授权...", "授权检查", 101)
                } else {
                    ProgressUpdatePop.updateProgress(100, "已完成授权检查...", "授权检查", 101)
                }
                delayEnd(t,mTermNum)
            }
        })
    }
}